import { create } from 'zustand'
import { TAB_KEY_SORT_FIVE } from '../constants/index'
import getSortFiveData from '../data/sortFive'
import getSevenStarData from '../data/sevenStar'

const PAGE_TOTAL_CACHE_KEY = 'page_total_cache_key'
const cachePageTotal = window.localStorage.getItem(PAGE_TOTAL_CACHE_KEY)

const useDataLimit = create((set, get) => {
    return {
        pageSize: cachePageTotal ? parseInt(cachePageTotal) : 10,
        setPageSize: async (pageSize) => {
            window.localStorage.setItem(PAGE_TOTAL_CACHE_KEY, pageSize)
            set({
                pageSize
            })
        },
    }
})

const useStore4SortFiveData = create((set, get) => {
    return {
        sortFiveData: null,
        setSortFiveData: async (pageSize, reFetch = false) => {
            try {
                const res = await getSortFiveData(pageSize, reFetch)
                set({
                    sortFiveData: res
                })
            } catch (error) {
                throw error
            }
        },
    }
})

const useStore4SevenStarData = create((set, get) => {
    return {
        sevenStarData: null,
        setSevenStarData: async (pageSize, reFetch = false) => {
            try {
                const res = await getSevenStarData(pageSize, reFetch)
                set({
                    sevenStarData: res
                })
            } catch (error) {
                throw error
            }
        },
    }
})

const useStore4Tabs = create((set, get) => {
    return {
        key: TAB_KEY_SORT_FIVE,
        badge4SortFive: 0,
        badge4SevenStar: 0,
        setKey: (key) => {
            set({
                key: key
            })
        },
        setBadge4SortFive: (v) => {
            set({
                badge4SortFive: v
            })
        },
        setBadge4SevenStar: (v) => {
            set({
                badge4SevenStar: v
            })
        }
    }
})

const useStore4Analysis = create((set, get) => {
    return {
        periodCount: 500,
        setPeriodCount: (count) => {
            set({
                periodCount: count
            })
        }
    }
})

export {
    useDataLimit,
    useStore4SortFiveData,
    useStore4SevenStarData,
    useStore4Tabs,
    useStore4Analysis,
}
